import React, { Component } from 'react';
import MapLogo from '@/assets/images/map/logo.png'
import MapStore from '@/assets/images/map/store.png'
import './style.less'
import { Input, Space } from 'antd'
const { Search } = Input;
const aMapKey = '29b19cff715886412c8c500e1f1d9831'

const hqmStoreLngLat = [126.532603, 45.727034]
let AMap = null //地图实例
let hqmMap = null //地图图层
let overlays = []  //监听draw事件可获取画好的覆盖物
export default class Map extends Component {
    constructor() {
        super()

        this.state = {
            tools: [{ type: 'marker', label: '画点' }],
            drawType: '',
            pois: []
        }
    }
    componentDidMount() {
        let script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = `https://webapi.amap.com/maps?v=1.4.15&key=${aMapKey}&callback=init`;
        document.getElementById('container').appendChild(script);
        window.init = () => {
            AMap = window.AMap
            hqmMap = new AMap.Map('map', {
                zoom: 15,  //设置地图显示的缩放级别
                center: hqmStoreLngLat,//设置地图中心点坐标

                viewMode: '2D',  //设置地图模式
                lang: 'zh_cn',  //设置地图语言类型
                resizeEnable: true
            });
            hqmMap.on('complete', () => {  // 地图图块加载完成后触发
                this.initMap()
                if (this.props.data.length > 0) {
                    this.setState({
                        drawType:'marker'
                    })
                    const storeIcon = new AMap.Icon({
                        // 图标尺寸
                        size: new AMap.Size(40, 50),
                        // 图标的取图地址
                        image: MapStore,
                        // 图标所用图片大小
                        imageSize: new AMap.Size(40, 50),
                        // 图标取图偏移量
                        imageOffset: new AMap.Pixel(0, 0)
                    });
                    this.drawMarker(this.props.data,'',storeIcon)
                }
            });
        }
    }
    initMap() {
        // 哈奇马门店位置扎点
        const hqmLogo = new AMap.Icon({
            // 图标尺寸
            size: new AMap.Size(40, 50),
            // 图标的取图地址
            image: MapLogo,
            // 图标所用图片大小
            imageSize: new AMap.Size(40, 50),
            // 图标取图偏移量
            imageOffset: new AMap.Pixel(0, 0)
        });

        this.drawMarker(hqmStoreLngLat, '哈奇马生活体验馆', hqmLogo, false)
        hqmMap.on('click', async (e) => {
            const self = this
            self.setState({
                pois: []
            })
            const location = [e.lnglat.getLng(), e.lnglat.getLat()]
            // console.log(`您在 [ ${e.lnglat.getLng() + ',' + e.lnglat.getLat()}] 的位置单击了地图！`)
            const { drawType } = this.state
            switch (drawType) {
                case 'marker':
                    this.clear()
                    const storeIcon = new AMap.Icon({
                        // 图标尺寸
                        size: new AMap.Size(40, 50),
                        // 图标的取图地址
                        image: MapStore,
                        // 图标所用图片大小
                        imageSize: new AMap.Size(40, 50),
                        // 图标取图偏移量
                        imageOffset: new AMap.Pixel(0, 0)
                    });
                    this.drawMarker(location,'',storeIcon)
                    const geo = await this.mapRegeo(location)
                    // console.log(geo)
                    if (geo.info === 'OK' && geo.infocode === "10000") {
                        const { addressComponent, formatted_address } = geo.regeocode
                        self.props.getRegeo({
                            type: 'success',
                            city: addressComponent.city,
                            cityCode: addressComponent.cityCode,
                            district: addressComponent.district,
                            province: addressComponent.province,
                            country: addressComponent.country,
                            adcode: addressComponent.adcode,
                            streetNumber: addressComponent.streetNumber,
                            address: formatted_address
                        })
                    } else {
                        this.props.getRegeo({
                            type: 'error',
                            errinfo: geo
                        })
                    }
                    break;
                default:
                    break;
            }
        });

    }
    search = async (e) => {
        const res = await this.mapSearchPlace(e)
        console.log(res, 'rrr')
        if (res.info === 'OK' && res.infocode === "10000") {
            this.setState({
                pois: res.pois
            })
        }
    }
    /**
     * @description 逆地理解析
     * @param {Array} location 经纬度
     */
    mapRegeo(location) {
        return new Promise((resolve, reject) => {
            fetch(`https://restapi.amap.com/v3/geocode/regeo?key=${aMapKey}&location=${location.join(',')}`, {
                method: "get",
            }).then((res) => {
                resolve(res.json())
            }).catch(err => {
                reject(err)
            })
        })
    }

    /**
     * @description 关键字搜索 API 服务地址
     * @param {*} keywords 关键字
     */
    mapSearchPlace(keywords) {
        return new Promise((resolve, reject) => {
            fetch(` https://restapi.amap.com/v5/place/text?key=${aMapKey}&keywords=${keywords}`, {
                method: "get",
            }).then((res) => {
                resolve(res.json())
            }).catch(err => {
                reject(err)
            })
        })

    }
    /**
     * @description 地理解析
     * @param {*} address 地址文字
     */
    mapGeo(address) {
        return new Promise((resolve, reject) => {
            fetch(` https://restapi.amap.com/v3/geocode/geo?key=${aMapKey}&address=${address}`, {
                method: "get",
            }).then((res) => {
                resolve(res.json())
            }).catch(err => {
                reject(err)
            })
        })
    }
    /**
     * @description 地图扎点
     * @param {*} lngLat 点的经纬度
     * @param {*} title 文字描述
     * @param {*} icon 自定义图标
     * @param {*} isJoinOverlays 是否加入存储图层数据
     * @returns 扎点实例
     */
    drawMarker(lngLat, title, icon, isJoinOverlays = true) {
        const marker = new AMap.Marker({
            position: lngLat,
            offset: new AMap.Pixel(-10, -10),
            title: title,
            icon: icon
        });
        isJoinOverlays && overlays.push(marker)//存储图层数据
        hqmMap.add(marker);//绘制数据
    }
    destroyMap() {
        hqmMap.off('click');//事件注销
        hqmMap && hqmMap.destroy();//地图销毁
    }
    draw(tool) {
        // 设置当前绘制类型
        this.setState({
            drawType: tool.type,
            pois: []
        })
    }
    // 关闭绘制功能
    closeDraw() {
        // 关闭绘制
        this.setState({
            pois: []
        })
        this.setState({
            drawType: ''
        })
    }
    // 清除地图图层数据
    clear() {
        hqmMap.remove(overlays)
        this.props.clear()
        this.props.getRegeo({
            type: 'clear'
        })
        this.setState({
            pois: []
        })
    }
    choosePois(item) {
        hqmMap.setCenter(item.location.split(','))
        hqmMap.setZoom(14)
        this.setState({
            pois: []
        })
    }
    render() {
        const { tools, drawType, pois } = this.state
        return (
            <div className='container' id='container'>
                <div className='map' id="map" >
                    <div className='search'>
                        <Search
                            placeholder="请输入地址信息"
                            allowClear
                            enterButton="搜索"
                            size="large"
                            onSearch={(e) => this.search(e)}

                        />
                        <div className='pois'>

                            {
                                pois.map(item => <div className='poi' onClick={() => this.choosePois(item)}>{item.name}</div>)
                            }
                        </div>
                    </div>
                    <div className='tools'>
                        <div className='list'>
                            {
                                tools.map(tool => <span style={{ color: drawType === tool.type ? '#3eaff8' : '' }} onClick={() => this.draw(tool)} className={`li ${drawType === tool.type ? 'choose' : 'unChoose'}`} >{tool.label}</span>)
                            }
                        </div>
                        <div className="btn">
                            <div className='closeDraw' onClick={() => this.clear()}>清除</div>
                            <div className='closeDraw' onClick={() => this.closeDraw()}>关闭绘图</div>
                        </div>
                    </div>
                </div>
            </div >
        );
    }
}
